package com.yipao.wx.task;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.yipao.core.system.SystemConfig;
import com.yipao.core.task.Task;
import com.yipao.core.util.BeanUtil;
import com.yipao.db.domain.Order;
import com.yipao.db.domain.order.OrderGoods;
import com.yipao.db.service.goods.GoodsProductService;
import com.yipao.db.service.order.OrderGoodsService;
import com.yipao.db.service.order.OrderService;
import com.yipao.db.util.OrderUtil;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 处理订单延时任务
 *
 * @author tianhao
 */
public class OrderUnpaidTask extends Task {
    private final Log logger = LogFactory.getLog(OrderUnpaidTask.class);
    private int orderId = -1;

    public OrderUnpaidTask(Integer orderId, long delayInMilliseconds) {
        super("OrderUnpaidTask-" + orderId, delayInMilliseconds);
        this.orderId = orderId;
    }

    public OrderUnpaidTask(Integer orderId) {
        super("OrderUnpaidTask-" + orderId, SystemConfig.getOrderUnpaid() * 60 * 1000);
        this.orderId = orderId;
    }

    @Override
    public void run() {
        logger.info("系统开始处理延时任务---订单超时未付款---" + this.orderId);

        OrderService orderService = BeanUtil.getBean(OrderService.class);
        OrderGoodsService orderGoodsService = BeanUtil.getBean(OrderGoodsService.class);
        GoodsProductService productService = BeanUtil.getBean(GoodsProductService.class);

        Order order = orderService.findById(this.orderId);
        if (order == null) {
            return;
        }
        if (!OrderUtil.isCreateStatus(order)) {
            return;
        }

        // 设置订单已取消状态
        order.setOrderStatus(OrderUtil.STATUS_CANCEL);
        order.setEndTime(LocalDateTime.now());
        if (orderService.updateWithOptimisticLocker(order) == 0) {
            throw new RuntimeException("更新数据已失效");
        }
        logger.info("系统结束处理延时任务---订单超时未付款---" + this.orderId);
    }
}
